package org.test.thrift.impl;

import org.apache.thrift.TException;
import org.apache.thrift.TProcessorFactory;
import org.apache.thrift.protocol.TCompactProtocol;
import org.apache.thrift.server.TServer;
import org.apache.thrift.server.TSimpleServer;
import org.apache.thrift.server.TThreadPoolServer;
import org.apache.thrift.transport.TFramedTransport;
import org.apache.thrift.transport.TServerSocket;
import org.apache.thrift.transport.TServerTransport;
import org.test.thrift.Test1;

public class ThriftServer implements Test1.Iface {

	@Override
	public void ping(int length) throws TException {
		// TODO Auto-generated method stub
		System.out.println(length);
	}

	public static void main(String[] args) {
		try {
			TServerTransport serverTransport = new TServerSocket(9090,60);
			//根据thrift实现类的一个对象作为服务器端的处理者（processor）
			Test1.Processor<ThriftServer> serverProcessor = new Test1.Processor(new ThriftServer());
			TThreadPoolServer.Args serverArgs=new TThreadPoolServer.Args(serverTransport);
			//数据传输格式，服务器端默认为TBinaryProtocol，服务器端和客户端要一致
			serverArgs.protocolFactory(new TCompactProtocol.Factory());
			//数据传输方式,默认应该是TIOStreamTransport，服务器端和客户端要一致
			serverArgs.transportFactory(new TFramedTransport.Factory());
			//把processor放入单例工厂，形成单例
			serverArgs.processorFactory(new TProcessorFactory(serverProcessor));

			/**
			 * TSimpleServer – 简单的单线程服务模型，常用于测试
			 * TThreadPoolServer – 多线程服务模型，使用标准的阻塞式IO。
			 * TNonblockingServer – 多线程服务模型，使用非阻塞式IO（需使用TFramedTransport数据传输方式）,nio实现
			 */
			TServer server = new TThreadPoolServer(serverArgs);

			System.out.println("Starting the server...");
			server.serve();

		} catch (Exception x) {
			x.printStackTrace();
		}
		System.out.println("done.");
	}

}
